package weibo;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

public class WeiboCrackerUtils {

	public static boolean isBlackLikeColor(Color color) {
		return color.getRed() < 20 && color.getGreen() < 20
				&& color.getBlue() < 20;
	}

	public static boolean isWhiteLikeColor(Color color) {
		return color.getRed() > 250 && color.getGreen() > 250
				&& color.getBlue() > 250;
	}

	public static boolean isLightColor(int rgb) {
		int r = (rgb >> 16) & 0xff;
		int g = (rgb >> 8) & 0xff;
		int b = (rgb) & 0xff;

		return r >= 128 && g >= 128 && b >= 128;
	}

	public static Color getColorByXY(BufferedImage cImg, int x, int y) {
		int rgb = cImg.getRGB(x, y);
		return new Color(rgb);
	}

	public static String imageToString(BufferedImage cimg) {
		StringBuilder builder = new StringBuilder();
		for (int x = 0; x < cimg.getWidth(); x++) {
			for (int y = 0; y < cimg.getHeight(); y++) {
				if (isWhiteLikeColor(getColorByXY(
						cimg, x, y))) {
					builder.append(0);
				} else {
					builder.append(1);
				}
			}
		}
		return builder.toString();
	}

	public static String getMostSimilarLetter(BufferedImage image)
			throws Exception {
		final String origin = imageToString(image);
		int min = 100;
		String letter = null;
		File[] letterDirs = new File("/Users/henrylian/Desktop/lab/letters")
				.listFiles();
		for (File letterDir : letterDirs) {
			if (!letterDir.isDirectory()) {
				continue;
			}
			File[] letters = letterDir.listFiles();
			for (File letterFile : letters) {
				BufferedImage img = ImageIO.read(letterFile);
				if(img == null){
					continue;
				}
				String source = imageToString(img);
				int curDistance = StringUtils.getLevenshteinDistance(source,
						origin);
				if (curDistance <= min) {
					letter = letterDir.getName();
					min = curDistance;
				}
			}
		}
		return letter;
	}
}
